﻿using System;
using System.Data;
using System.Linq;
using Model;

namespace BLL
{
    public class Sys_Enterprise_BLL
    {
        ExtendedDBModelContainer _db = new ExtendedDBModelContainer();

        public IQueryable<Sys_Enterprise> Get()
        {
            return _db.Sys_Enterprise.OrderBy(a => a.EnterpriseName);
        }

        public Sys_Enterprise Get(Guid? Id)
        {
            var item = new Sys_Enterprise();

            if (Id.HasValue)
            {
                item = _db.Sys_Enterprise.Single(a => a.Id.Equals(Id.Value));
            }
            return item;
        }

        public void Save(Guid? Id, ref Sys_Enterprise item)
        {
            if (!Id.HasValue)
            {
                //新建企业的时候默认增加 一个部门架构

                var _Sys_Organizations = new Sys_Organizations() { Department = "总公司", DepartmentCode = "001", SystemCode = "001", Remarks = "系统默认根节点" };
                item.Sys_Organizations.Add(_Sys_Organizations);
                _db.Sys_Enterprise.AddObject(item);

            }
            else
            {
                _db.Sys_Enterprise.Attach(item);
                _db.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
            }
            _db.SaveChanges();
        }

        public void Save()
        {
            _db.SaveChanges();
        }

        public void Delete(Guid Id)
        {
            _db.Sys_Enterprise.DeleteObject(_db.Sys_Enterprise.Single(a => a.Id == Id));
            _db.SaveChanges();
        }
    }
}
